package ssw.game.engine;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.SortedSet;

import ssw.game.GameType;

public class ComputeTiles {
	private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	private final Random random = new Random();
	private final List<String> remainingWords;
	private String tiles = "";
	private final int numberOfTiles;
	
	private ComputeTiles(SortedSet<String> words, GameType type)  {
		super();
		remainingWords = new ArrayList<String>(words);
		numberOfTiles = type.getNumberOfTiles();
	}
	
	static Collection<String> with(SortedSet<String> words, GameType type)  {
		ComputeTiles ct = new ComputeTiles(words, type);
		ct.go();
		List<String> listOfTiles = new ArrayList<String>();
		for (char c : ct.tiles.toCharArray())  {
			listOfTiles.add(String.valueOf(c));
		}
		return listOfTiles;
	}

	void go()  {
		while (tiles.length() < numberOfTiles)  {
			String sortedWord = ALPHABET;
			if (!remainingWords.isEmpty())  {
				int chosenPlace = random.nextInt(remainingWords.size());
				String chosenWord = remainingWords.remove(chosenPlace);
				sortedWord = sortWord(chosenWord);
			}
			
			doSortedWord(sortedWord, 0);
		}
	}
	
	void doSortedWord(String sortedWord, int place)  {
		if ((sortedWord.length() == 0) || (tiles.length() >= numberOfTiles))  {
			return;
		}
		
		String nextLetter = sortedWord.substring(0, 1);
		int find = tiles.indexOf(nextLetter, place);
		if (find < 0)  {
			tiles = sortWord(tiles + nextLetter);
			doSortedWord(sortedWord.substring(1), 1 + tiles.lastIndexOf(nextLetter));
		}
		else  {
			doSortedWord(sortedWord.substring(1), find + 1);
		}
	}
	
	static String sortWord(String normalWord)  {
		char[] letters = normalWord.toCharArray();
		Arrays.sort(letters);
		return new String(letters);
	}
}
